package com.coolweather.android;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.coolweather.android.db.City;
import com.coolweather.android.db.County;
import com.coolweather.android.db.Province;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;
import org.litepal.tablemanager.Connector;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ChooseFra extends Fragment {
    private ArrayAdapter arrayAdapter;
    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;
    private List<String> datalist = new ArrayList<String>();
    public int provinceId = 0;
    public int cityId = 0;
    public int temp = 0;//0省 1市 2县
    private ListView list;
    private Handler mHandler = new Handler();
    private Button backButton;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.drablelist, container, false);
        Connector.getDatabase();
        backButton = (Button) view.findViewById(R.id.back_button);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (temp == 1) {
                    Log.d("info", "btn1方法");
                    provinceList = DataSupport.findAll(Province.class);
                    datalist.clear();
                    for (Province province : provinceList) {
                        datalist.add(province.getProvinceName());
                    }
                    arrayAdapter.notifyDataSetChanged();
                    temp = 0;
                } else if (temp == 2) {
                    Log.d("info", "btn2方法");
                    cityList = DataSupport.findAll(City.class);
                    datalist.clear();
                    for (City city : cityList) {
                        datalist.add(city.getCityName());
                    }
                    arrayAdapter.notifyDataSetChanged();
                    temp = 1;
                }
            }
        });
        list = (ListView) view.findViewById(R.id.list_view);
        arrayAdapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_list_item_1,
                datalist);
        list.setAdapter(arrayAdapter);
        provinceList = DataSupport.findAll(Province.class);
        Log.d("info", String.valueOf(provinceList.size()));
        if (provinceList.size() > 0) {
            datalist.clear();
            for (Province province : provinceList) {
                datalist.add(province.getProvinceName());
            }
            arrayAdapter.notifyDataSetChanged();
        } else {
            String address = "http://guolin.tech/api/china";
            queryDataFromServer(address, "province");
        }
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (temp) {
                    case 0:
                        Log.d("info", "item0方法");
                        Province pro1 = provinceList.get(i);
                        provinceId = pro1.getProvinceCode();
                        cityList = DataSupport.where("provinceId=?",
                                String.valueOf(provinceId)).find(City.class);
                        Log.d("info", "itemo查数据库里" + String.valueOf(cityList.size()));
                        if (cityList.size() > 0) {
                            datalist.clear();
                            for (City city : cityList) {
                                datalist.add(city.getCityName());
                            }
                            arrayAdapter.notifyDataSetChanged();
                            temp = 1;
                        } else {
                            String address = "http://guolin.tech/api/china/" + provinceId;
                            queryDataFromServer(address, "city");
                        }
                        break;
                    case 1:
                        Log.d("info", "item1方法");
                        City city = cityList.get(i);
                        cityId = city.getCityCode();
                        countyList = DataSupport.where("cityId=?",
                                String.valueOf(cityId)).find(County.class);
                        Log.d("info", "item1查数据库方法" + String.valueOf(countyList.size()));
                        if (countyList.size() > 0) {
                            datalist.clear();
                            for (County county : countyList) {
                                datalist.add(county.getCountyName());
                            }
                            arrayAdapter.notifyDataSetChanged();
                            temp = 2;
                        } else {
                            String address = "http://guolin.tech/api/china/" + provinceId + "/" + cityId;
                            queryDataFromServer(address, "county");
                        }
                        break;
                    case 2:
                        County county = countyList.get(i);
                        Log.d("info", county.toString());
                        if (getActivity() instanceof MainActivity) {
                            Intent intent = new Intent(getActivity(), WeatherActivity.class);
                            intent.putExtra("weather_id", county.getWeatherId());
                            startActivity(intent);
                            getActivity().finish();
                        } else if (getActivity() instanceof WeatherActivity) {
                            WeatherActivity activity = (WeatherActivity) getActivity();
                            activity.drawerLayout.closeDrawers();
                            activity.swipeRefresh.setRefreshing(true);
                            String address = "http://guolin.tech/api/weather?cityid=" + county.getWeatherId() + "&key=bc0418b57b2d4918819d3974ac1285d9";
                            activity.queryDataFromServer(address);
                            temp = 0;
                            activity.swipeRefresh.setRefreshing(false);
                            freshProUi();
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }
    /**
     * 刷新省份ui办法
     */
    public void freshProUi() {
        provinceList = DataSupport.findAll(Province.class);
        Log.d("info", String.valueOf(provinceList.size()));
        datalist.clear();
        for (Province province : provinceList) {
            datalist.add(province.getProvinceName());
        }
        arrayAdapter.notifyDataSetChanged();
    }

    /**
     * 刷新城市ui办法
     */
    public void freshCityUi() {
        Log.d("info", String.valueOf(provinceId));
        cityList = DataSupport.where("provinceId=?",
                String.valueOf(provinceId)).find(City.class);
        Log.d("info", String.valueOf(cityList.size()));
        if (cityList.size() > 0) {
            datalist.clear();
            for (City city : cityList) {
                datalist.add(city.getCityName());
            }
            arrayAdapter.notifyDataSetChanged();
        }
        temp = 1;
    }

    /**
     * 刷新乡村ui办法
     */
    public void freshCountryUi() {
        Log.d("info", String.valueOf(provinceId + 99 + cityId));
        countyList = DataSupport.where("cityId=?",
                String.valueOf(cityId)).find(County.class);
        Log.d("info", String.valueOf(countyList.size()));
        if (countyList.size() > 0) {
            datalist.clear();
            for (County county : countyList) {
                datalist.add(county.getCountyName());
            }
            arrayAdapter.notifyDataSetChanged();
        }
        temp = 2;
    }

    /**
     * 封装http请求获取数据
     *
     * @param address 请求地址
     * @param type    类型
     */
    private void queryDataFromServer(final String address, final String type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(address).build();
                    client.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String responseData = response.body().string();
                            Log.d("responseData", responseData);
                            if ("province".equals(type)) {
                                handleProvinceResponse(responseData);
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        freshProUi();
                                    }
                                });
                            } else if ("city".equals(type)) {
                                handleCityResponse(responseData, provinceId);
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        freshCityUi();
                                    }
                                });
                            } else if ("county".equals(type)) {
                                handleCountryResponse(responseData, cityId);
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        freshCountryUi();
                                    }
                                });
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 存储省份数据
     *
     * @param response
     * @return
     */
    static boolean handleProvinceResponse(String response) {
        Log.d("info", "写入省市数据");
        if (!TextUtils.isEmpty(response)) {
            try {
                DataSupport.deleteAll(Province.class);
                JSONArray allprovince = new JSONArray(response);
                for (int i = 0; i < allprovince.length(); i++) {
                    JSONObject provinceObject = allprovince.getJSONObject(i);
                    Province province = new Province();
                    province.setId(provinceObject.getInt("id"));
                    province.setProvinceName(provinceObject.getString("name"));
                    province.setProvinceCode(provinceObject.getInt("id"));
                    province.assignBaseObjId(0);
                    province.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 存储城市信息
     *
     * @param response   城市体
     * @param provinceId 省份id
     * @return
     * @throws JSONException
     */
    static boolean handleCityResponse(String response, int provinceId) {
        if (!TextUtils.isEmpty(response)) {
            try {
                DataSupport.deleteAll(City.class);
                JSONArray allCity = new JSONArray(response);
                for (int i = 0; i < allCity.length(); i++) {
                    JSONObject cityObject = allCity.getJSONObject(i);
                    City city = new City();
                    city.setCityCode(cityObject.getInt("id"));
                    city.setCityName(cityObject.getString("name"));
                    city.setProvinceId(provinceId);
                    city.assignBaseObjId(0);
                    city.save();
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 存储县级数据
     *
     * @param responseData
     * @param cityId       城市id
     * @return
     */
    static boolean handleCountryResponse(String responseData, int cityId) {
        Log.d("info", "写入县数据");
        if (!TextUtils.isEmpty(responseData)) {
            try {
                DataSupport.deleteAll(County.class);
                JSONArray allCountry = new JSONArray(responseData);
                for (int i = 0; i < allCountry.length(); i++) {
                    JSONObject countryObject = allCountry.getJSONObject(i);
                    County county = new County();
                    county.setId(countryObject.getInt("id"));
                    county.setCountyName(countryObject.getString("name"));
                    county.setCityId(cityId);
                    county.setWeatherId(countryObject.getString("weather_id"));
                    county.assignBaseObjId(0);
                    county.save();
                }
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
